<?php
include 'includes/header.php';
require_once 'config/database.php';

if (isset($_SESSION['user_id'])) {
    redirect('profile.php');
}

if (isset($_SESSION['is_admin']) && $_SESSION['is_admin']) {
    header('Location: admin/index.php');
    exit();
}

if (isset($_POST['login'])) {
    $database = new Database();
    $db = $database->getConnection();
    
    $email = sanitize_input($_POST['email']);
    $password = $_POST['password'];
    
    $query = "SELECT id, password, is_admin FROM users WHERE email = ?";
    $stmt = $db->prepare($query);
    $stmt->execute([$email]);
    
    if ($user = $stmt->fetch()) {
        if (password_verify($password, $user['password'])) {
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['is_admin'] = $user['is_admin'];
            set_message('Welcome back!');
            redirect('admin/index.php');
        }
    }
    
    set_message('Invalid email or password', 'danger');
    display_message();
}
?>

<div class="container py-5">
    <div class="row justify-content-center">
        <div class="col-md-6">
            <div class="card shadow">
                <div class="card-body p-5">
                    <h2 class="text-center mb-4">Login</h2>
                    
                    <form method="POST">
                        <div class="mb-3">
                            <label class="form-label">Email</label>
                            <input type="email" class="form-control" name="email" required>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Password</label>
                            <input type="password" class="form-control" name="password" required>
                        </div>
                        
                        <div class="d-grid">
                            <button type="submit" name="login" class="btn btn-primary">Login</button>
                        </div>
                        
                        <p class="text-center mt-3">
                            Don't have an account? <a href="/register.php">Register here</a>
                        </p>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<?php include 'includes/footer.php'; ?> 